package cn.caplike.demo.repository.java.concurrency.reentrantlock.extend;

import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description: 写一个固定容量同步容器，拥有put和get方法，以及getCount方法
 * 能够支持两个生产者线程以及10个消费者线程的阻塞调用
 * <p>
 * 使用Lock和Condition来实现
 * 对比两种方式，condition的方式可以更加精确的指定哪些线程被唤醒
 */
public class ConditionalContainer<T> {
    static final private int max = 10;   // 最多10个元素
    final private LinkedList<T> lists = new LinkedList<>();
    private int count = 0;
    private final Lock lock = new ReentrantLock();
    private final Condition producer = lock.newCondition();
    private final Condition consumer = lock.newCondition();

    public static void main(String[] args) {
        // @formatter:off
        ConditionalContainer<String> container = new ConditionalContainer<>();

        // ~ 启动消费者线程
        for (int idx = 0; idx < 10; idx++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println("[" + Thread.currentThread().getName() + "]" + " 获取生产者的产品: " + container.get());
                }
            }, "consumer-thread-" + idx).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException ignored) {}

        // ~ 启动生产者线程
        for (int idx = 0; idx < 2; idx++) {
            new Thread(() -> {
                for (int j = 0; j < 25; j++) {
                    container.put("生产者#" + new DecimalFormat("00").format(j));
                }
            }, "producer-thread-" + idx).start();
        }
        // @formatter:on
    }

    public void put(T t) {
        lock.lock();
        try {
            while (lists.size() == max) {  // 想想为什么用while而不是用if
                producer.await();
            }
            lists.add(t);
            ++count;
            consumer.signalAll();// 通知消费者线程进行消费
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public T get() {
        T t = null;
        lock.lock();
        try {
            while (lists.size() == 0) {
                consumer.await();
            }
            t = lists.removeFirst();
            count--;
            producer.signalAll();   // 通知生产者进行生产
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }
}